﻿using System;
using System.Linq;
using System.Reflection;
using Linq2Crm.ObjectModel.Attributes;

namespace Linq2Crm.ObjectModel
{
	public class AttributeParser
	{
		public Type DomainObjectType { get; set; }		
		public AnalyzeResult AnalyzeResult { get; set; }

		public AttributeParser(Type domainObject)
		{
			DomainObjectType = domainObject;			
		}		

		public AnalyzeResult AnalyzeType()
		{			
			AnalyzeResult result = new AnalyzeResult();
			foreach (object o in DomainObjectType.GetCustomAttributes(true))
			{
				CrmEntityMappingAttribute crmEntityMappingAttribute = o as CrmEntityMappingAttribute;
				if (crmEntityMappingAttribute != null)
				{
					result.EntityName = crmEntityMappingAttribute.EntitySchemaName;
					if (crmEntityMappingAttribute.IgnoreProperties != null)
					{
						result.IgnoreFields.AddRange(crmEntityMappingAttribute.IgnoreProperties);
					}
					
					result.FieldsList.Add(crmEntityMappingAttribute.IDField);
					if (!String.IsNullOrEmpty(crmEntityMappingAttribute.NameField))
					{
						result.FieldsList.Add(crmEntityMappingAttribute.NameField);
					}

					if (!result.IgnoreFields.Any(x=>x.Equals("statecode", StringComparison.OrdinalIgnoreCase)))
					{
						result.FieldsList.Add("statecode");	
					}
					if (!result.IgnoreFields.Any(x => x.Equals("statuscode", StringComparison.OrdinalIgnoreCase)))
					{
						result.FieldsList.Add("statuscode");
					}
				}				
			}

			foreach (PropertyInfo propertyInfo in DomainObjectType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
			{
				if (result.IgnoreFields.Contains(propertyInfo.Name)) continue;

				foreach (object o in propertyInfo.GetCustomAttributes(typeof(CrmFieldMappingAttribute), false))
				{
					CrmFieldMappingAttribute crmFieldMappingAttribute = o as CrmFieldMappingAttribute;
					if (crmFieldMappingAttribute != null)
					{
						var colName = (crmFieldMappingAttribute).SchemaName;
						if (result.FieldsList.Contains(colName)) continue;
						result.FieldsList.Add(colName);
					}
				}
			}
			AnalyzeResult = result;
			return result;
		}	
	}
}